package cn.acheng1314.springboot2.controller

import cn.acheng1314.springboot2.BaseTest
import cn.acheng1314.springboot2.dto.HousePropertyDTO
import com.alibaba.fastjson.JSONObject
import org.junit.Before
import org.junit.Test
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import java.nio.charset.Charset


internal class HouseControllerTest : BaseTest() {

    private val log = LoggerFactory.getLogger(this::class.java)

    @Autowired
    private lateinit var webApplicationContext: WebApplicationContext

    private lateinit var mockMvc: MockMvc

    @Before
    @Throws(Exception::class)
    fun setUp() {
        //MockMvcBuilders.webAppContextSetup(WebApplicationContext context)：指定WebApplicationContext，将会从该上下文获取相应的控制器并得到相应的MockMvc；
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build() //建议使用这种
    }

    @Test
    fun saveHouse() {

        val contentStr = "{\"areaDescription\":\"深圳市宝安区xx街道\",\"areaId\":9999,\"coveredArea\":999.99,\"description\":\"天下第二楼盘，好用又好看\",\"developer\":\"第二开发商\",\"floorArea\":10000.0,\"greenRate\":\"88%\",\"housePeriod\":\"99楼\",\"level\":\"现卖5、10、13-19层\",\"name\":\"天下最大楼盘\",\"plotRatio\":\"78%\",\"propertyCompany\":\"甲乙天下物业有限公司\",\"propertyPrice\":\"2.35元/㎡\",\"propertyType\":\"物业类型\",\"remark\":\"这是测试信息\",\"totalHouse\":\"8888户\",\"transportation\":\"xx地铁口，右行300m公交车站\"}"

        var jsonContent = JSONObject.parseObject(contentStr).toJSONString()

        val house: HousePropertyDTO = JSONObject.parseObject(jsonContent, HousePropertyDTO::class.java)
        house.marker = "{\"longitude\":100.1,\"latitude\":100.1,\"title\":\"位置描述\"}"

        jsonContent = JSONObject.toJSONString(house)


        val responseString = mockMvc
                .perform(MockMvcRequestBuilders.post("/house/saveHouse") //请求的url,请求的方法是post
                        .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) //数据的格式
                        .characterEncoding(Charsets.UTF_8.name())
                        .content(jsonContent)
                        .accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(MockMvcResultMatchers.status().isOk) //返回的状态是200
                .andDo(MockMvcResultHandlers.print()) //打印出请求和相应的内容
                .andReturn().response.getContentAsString(Charsets.UTF_8) //将相应的数据转换为字符


        log.info(responseString)
    }

    @Test
    fun saveHouseExtend() {
    }

    @Test
    fun saveHouseNews() {
    }
}